<template>
  <view class="container">
    <scroll-view
      :scroll-x="true"
      :enhanced="true"
      :show-scrollbar="false"
      :scroll-into-view="'user_' + selectedId"
      :scroll-anchoring="true"
      :scroll-with-animation="true"
      class="user-list-scroll-view"
      @scroll="handleScroll"
    >
      <view class="user-list">
        <UserItem
          v-for="(item, index) in registerIdAppUserInfos"
          :id="'user_' + item.appUserInfoId"
          :key="index"
          :data="item"
          :selectedId="selectedId"
          @click="handleClick"
          @setItemNodeInfo="(data:any) => (userListWidth = data.width + gap)"
        />
        <view style="padding: 0 18rpx;">
          <text style="opacity: 0;">1</text>
        </view>
      </view>
    </scroll-view>
    <view class="tip-box">
      <view class="mask"></view>
      <view class="tip" @click="handleNextUserOrNextPage">
        <view class="tip-text">
          <text>{{ isLast ? '换一批' : '右滑' }}</text>
          <text class="ali-icon icon-you1"></text>
        </view>
        <text>{{ total }}人</text>
      </view>
    </view>
  </view>
</template>
<script setup lang="ts">
  import { computed, onMounted, ref, watch, type PropType } from 'vue';
  import UserItem from './UserItem.vue';
  import type { IActivityRegisterQuery, RegisterIdAppUserInfo } from '@/api/activity/types';
  import { getAppUserConnectionSquare } from '@/api/activity';
  import { Toast } from '@/utils';
  import { throttle } from 'lodash-es';

  const props = defineProps({
    activityId: {
      type: Number,
      default: undefined,
    },
    myUserInfo: {
      type: Object as PropType<RegisterIdAppUserInfo>,
      default: () => ({}),
    },
    maxLength: {
      type: Number,
      default: 0,
    },
  });
  let flag = true;
  const gap = uni.upx2px(32);

  const emits = defineEmits(['data']);

  const registerIdAppUserInfos = ref<RegisterIdAppUserInfo[]>([]);

  const activityRegisterQuery = ref<IActivityRegisterQuery>({
    activityId: props.activityId!,
    size: 50,
    current: 1,
  });

  const total = ref(0);

  const selectedId = ref();
  const userListWidth = ref(0);
  const currIndex = ref(0);

  const isLast = ref(false);

  const handleClick = throttle((user: RegisterIdAppUserInfo) => {
    handleSelected(user);
    emits('data', registerIdAppUserInfos.value, currIndex.value);
  }, 600);

  const handleSelected = (user: RegisterIdAppUserInfo) => {
    selectedId.value = user.appUserInfoId;
    const index = registerIdAppUserInfos.value.findIndex(
      (item) => item.appUserInfoId === user.appUserInfoId,
    );
    currIndex.value = index;
  };

  onMounted(() => {
    activityRegisterQuery.value.activityId = props.activityId!;
    queryAppUserConnectionSquare();
  });
  const pages = ref(0);
  const queryAppUserConnectionSquare = async () => {
    const res = await getAppUserConnectionSquare(activityRegisterQuery.value);
    registerIdAppUserInfos.value = res.records;
    activityRegisterQuery.value.current = res.current;
    activityRegisterQuery.value.size = res.size;
    pages.value = res.pages;
    total.value = res.total;
    if (res.current === 1) {
      setSelfUser();
    }

    setTimeout(() => {
      handleClick(res.records[0]);
    }, 100);
  };

  watch(
    () => props.myUserInfo,
    () => {
      setSelfUser();
    },
    { deep: true },
  );

  const setSelfUser = () => {
    if (!registerIdAppUserInfos.value.length) return;
    if (activityRegisterQuery.value.current !== 1) return;

    if (registerIdAppUserInfos.value.length > 6) {
      // 已存在更新
      if (registerIdAppUserInfos.value[5].appUserInfoId === props.myUserInfo.appUserInfoId) {
        registerIdAppUserInfos.value[5] = props.myUserInfo;
        return;
      }
      // 不存在插入
      registerIdAppUserInfos.value.splice(5, 0, props.myUserInfo);
      return;
    }

    if (registerIdAppUserInfos.value.at(-1)?.appUserInfoId === props.myUserInfo.appUserInfoId) {
      registerIdAppUserInfos.value[registerIdAppUserInfos.value.length - 1] = props.myUserInfo;
      return;
    }
    registerIdAppUserInfos.value.push(props.myUserInfo);
  };

  const handleNextPage = async () => {
    if (activityRegisterQuery.value.current === pages.value) {
      Toast('这是最后一位了');
      return;
    }
    if (!flag) return;
    try {
      flag = false;
      if (
        activityRegisterQuery.value.current !== 1 &&
        activityRegisterQuery.value.current! * activityRegisterQuery.value.size! >= total.value
      ) {
        return;
      } else if (registerIdAppUserInfos.value.length) {
        activityRegisterQuery.value.current!++;
      }
      await queryAppUserConnectionSquare();
    } catch (error) {
      Toast('加载失败');
    } finally {
      flag = true;
    }
  };

  const timer = ref<NodeJS.Timeout | null>(null);
  const isScrollIng = ref(false);
  const handleNextUserOrNextPage = () => {
    if (isScrollIng.value) return;
    if (isLast.value) {
      handleNextPage();
    } else {
      handleClick(registerIdAppUserInfos.value[currIndex.value + 1]);
    }
  };

  const handleNextUser = () => {
    if (isScrollIng.value) return;
    handleClick(registerIdAppUserInfos.value[currIndex.value + 1]);
  };

  const handleScroll = (event: any) => {
    console.log(userListWidth.value * 50);
    console.log(event.detail.scrollLeft);
    if (event.detail.scrollLeft > userListWidth.value * 50) {
      isLast.value = true;
    } else {
      isLast.value = false;
    }

    isScrollIng.value = true;
    if (timer.value) {
      clearTimeout(timer.value);
      timer.value = null;
    }
    timer.value = setTimeout(() => {
      isScrollIng.value = false;
    }, 300);
  };

  const handlePrevUser = () => {
    handleClick(registerIdAppUserInfos.value[currIndex.value - 1]);
  };

  defineExpose({
    handleClick,
    handleNextUser,
    handlePrevUser,
    handleSelected,
  });
</script>
<style lang="scss" scoped>
  .container {
    position: relative;
    padding: 0rpx 104rpx 16rpx 0;
    background-color: #f2f3f5;

    .user-list-scroll-view {
      .user-list {
        display: flex;
        align-items: center;
        gap: 16rpx;
        height: 224rpx;
        flex-wrap: nowrap;
      }
    }

    .tip-box {
      position: absolute;
      right: 0;
      top: 0;
      display: flex;
      height: 100%;

      .mask {
        width: 80rpx;
        height: 100%;
        background: linear-gradient(270deg, #f2f3f5 0%, rgba(242, 243, 245, 0) 100%);
      }

      .tip {
        display: flex;
        flex-direction: column;
        gap: 8rpx;
        font-size: 24rpx;
        color: #2878ff;
        line-height: 32rpx;
        background: #f2f3f5;
        justify-content: center;
        height: 100%;
        padding: 0 16rpx;

        .tip-text {
          display: flex;
          align-items: center;
        }
      }
    }
  }
</style>
